<template>
  <div>
    <div class="ele-page-header">
      <div class="ele-page-title">编辑资讯</div>
    </div>
    <el-form ref="demoForm" :model="form" :rules="rules" label-width="150px">
      <div class="ele-body">
        <el-card shadow="never">
          <el-form-item label="显示时间：" prop="showTime">
            <!-- <el-date-picker format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" v-model="form.showTime"
              type="datetime" placeholder="选择日期时间" style="width: 80%;">
            </el-date-picker> -->
            <!-- 输入时间 -->
            <el-input v-model="form.showTime" placeholder="请输入显示时间" clearable style="width: 80%;" />
          </el-form-item>
          <el-form-item label="标题：" prop="title">
            <el-input v-model="form.title" placeholder="请输入资讯标题" clearable style="width: 80%;" />
          </el-form-item>
          <el-form-item label="来源：" prop="sources">
            <el-input v-model="form.sources" placeholder="请输入资讯来源" clearable style="width: 80%;" />
          </el-form-item>
          <el-form-item label="简介：" prop="sketchs">
            <el-input type="textarea" v-model="form.sketchs" maxlength="200" show-word-limit placeholder="请输入资讯简介"
              clearable style="width: 80%;" />
          </el-form-item>
          <!-- 选择事件  -->
          <el-form-item label="分类：" prop="catid" v-if="false">
            <!-- 下拉 classifyList -->
            <el-select v-model="form.catid" placeholder="请选择资讯分类" clearable style="width: 80%;"
              @change="changeClassify">
              <el-option v-for="item in classifyList" :key="item.id" :label="item.catname" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="列表图：" prop="thumb">
            <upload-img class="logo" :type="uploadRules" v-model="form.thumb" :info="logoText">
            </upload-img>
          </el-form-item>

          <el-form-item label="推荐：" required v-if="false">
            <!-- 点击选中事件 -->
            <el-radio-group v-model="form.flag" :disabled="false" @change="changeFlag">
              <el-radio :label="0">无</el-radio>
              <el-radio :label="1">推荐到首页大图</el-radio>
              <el-radio :label="2">推荐到首页要闻</el-radio>
              <el-radio :label="3">推荐到首页列表小图</el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- 推荐的上传图片 isShowFlag -->
          <el-form-item label="推荐图：" v-if="isShowFlag">
            <el-radio-group v-model="form.recType" :disabled="false" @change="changeRec">
              <el-radio :label="1">使用列表图</el-radio>
              <el-radio :label="2">添加图片</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="" prop="recImg" v-if="isShowRecUpload">
            <upload-img class="logo" :type="uploadRules" v-model="form.recImg" :info="logoText1"></upload-img>
          </el-form-item>



          <el-form-item label="关键词：" prop="keywords">
            <el-input v-model="form.keywords" placeholder="请输入关键词，以逗号隔开（用于seo优化）" clearable style="width: 80%;" />
          </el-form-item>
          <el-form-item label="网站描述：" prop="description">
            <el-input type="textarea" v-model="form.description" maxlength="200" show-word-limit
              placeholder="请输入网站描述（用于seo优化）" clearable style="width: 80%;" />
          </el-form-item>

          <el-form-item label="详情：" prop="content">
            <tinymce-editor v-model="form.content" :init="config" />
          </el-form-item>

          <div class="add_header">
            <el-button @click="closeThis">取消 </el-button>
            <el-button type="primary" @click="submit">发布</el-button>
          </div>
        </el-card>
      </div>
    </el-form>
  </div>
</template>

<script>
import uploadImg from "@/components/upload-img";
// 要引入组件
import TinymceEditor from '@/components/TinymceEditor/index.vue';
import { addArticle, updateArticle, getArticle } from '@/api/article';
import request from '@/utils/request';
export default {
  components: {
    uploadImg,
    TinymceEditor,
  },
  name: "Articleedit",
  data() {
    return {
      uploadRules: ["image/jpeg", "image/jpg", "image/png"],
      logoText: "请上传列表图",
      logoText1: "请上传推荐图",
      isShowThumb: true,
      isShowFlag: false,
      isShowRecUpload: false,
      showTime: "",
      // 表单数据
      form: {
        flag: 0,
        recType: 1,
      },
      // 表单验证规则
      rules: {
        title: [{ required: true, message: "请输入资讯标题", trigger: "blur" }],
        // sketchs: [{ required: true, message: "请输入资讯简介", trigger: "blur" }],
        catid: [{ required: true, message: "请选择资讯分类", trigger: "blur" }],
        // keywords: [{ required: true, message: "请输入关键词", trigger: "blur" }],
        // description: [{ required: true, message: "请输入网站描述", trigger: "blur" }],
        thumb: [{ required: true, message: "请上传列表图", trigger: "blur" }],
        content: [{ required: true, message: "请输入详情", trigger: "blur" }],
      },
      // 分类列表
      classifyList: [],
      config: {
        height: 525,
        images_upload_handler: (blobInfo, success, error) => {
          const file = blobInfo.blob();
          // 使用 axios 上传，实际开发这段建议写在 api 中再调用 api
          const formData = new FormData();
          console.log(file);
          formData.append('file', file, file.name);
          request.post('/file/upload', formData).then(res => {
            if (res.data.data.url) {
              success(res.data.data.url);
            } else {
              error(res.data.message);
            }
          }).catch(e => {
            console.error(e);
            error(e.message);
          });
        }
      }
    };
  },
  created() {
    console.log('This is the created method.');
    if (this.$route.query.id) {
      this.getFormData(this.$route.query.id);
    }
    // this.getClassifyList();
    // showTime 默认为当前时间
    if (!this.$route.query.id) {
      // showTime 默认为当前时间 格式为 2021-01-01 00:00:00
      // const date = new Date().toLocaleString();
      // 格式改成 yyyy-mm-dd hh:mm:ss
      // this.form.showTime = date.replace(/\//g, "-");
      // 推荐默认无
      //   this.form.flag = 0;
    }
  },
  methods: {
    // 表单回显
    getFormData(id) {
      // getArticle
      getArticle(id).then((res) => {
        this.form = res;
      });
    },

    /* 提交 */
    submit() {
      this.$refs["demoForm"].validate(async valid => {
        if (!valid) {
          return false;
        }
        this.loading = true;
        const data = {
          ...this.form,
        };

        // 处理 data中的showTime 如果不为空 去除前后空格
        if (data.showTime) {
          data.showTime = data.showTime.trim();
        }

        const saveOrUpdate = this.isUpdate ? updateArticle : addArticle;
        saveOrUpdate(data)
          .then((msg) => {
            // this.loading = false;
            this.$message.success(msg);
            // 跳转到列表页面 /article/index
            this.$router.push({ name: "ArticleIndex" });
          })
          .catch((e) => {
            this.loading = false;
            this.$message.error(e.message);
          });
      });
    },
    // 时间选择器change
    pickerChange(val) {
      if (val) {
        this.form.startTime = val[0];
        this.form.endTime = val[1];
      }
    },

    /* 关闭当前页面 */
    closeThis() {
      this.$router.push({
        path: "./index",
      });
    },
    // changeClassify
    changeClassify(val) {
      // 如果是 9 10 11 12 13 14 15 16 中的一个
      var arr = [9, 10, 11, 12, 13, 14, 15, 16];
      if (arr.includes(val)) {
        this.isShowThumb = false;
      } else {
        this.isShowThumb = true;
      }
      console.log(val);
    },

    // changeFlag
    changeFlag(val) {
      // 如果是 1 2 3 中的一个
      var arr = [1, 2, 3];
      if (arr.includes(val)) {
        this.isShowFlag = true;
      } else {
        this.isShowFlag = false;
      }
      console.log(val);
    },

    // changeRec
    changeRec(val) {
      // 如果是 1 使用列表图 2 使用自定义图片 如果是 2 显示上传图片
      if (val === 2) {
        this.isShowRecUpload = true;
      } else {
        this.isShowRecUpload = false;
      }
    }

  },
};
</script>

<style lang="scss" scoped>
// add_header 内容居中
.add_header {
  text-align: center;
  margin-top: 20px;
}
</style>
